package engine.step;

import engine.GameEngine;
import engine.data.Building;
import engine.data.City;
import engine.data.Player;
import engine.data.Unit;

public final class CheckCitiesStep extends Step {

	private static Step step;

	public static synchronized Step getStep() {
		if (step == null)
			step = new CheckCitiesStep();
		return step;
	}

	public Step execute() {
		byte currCityIndex = GameEngine.currCityIndex;
		Player currPlayer = GameEngine.currPlayer;
		if (currCityIndex < currPlayer.cities.size()) {
			City city = (City) currPlayer.cities.get(currCityIndex);
			if (city.hasNewProduct) {
				if (city.buildingType != null) {
					if (city.buildingType.equals(Building.class))
						city.buildingRoster.add(new Byte(city.buildingId));
					if (city.buildingType.equals(Unit.class)) {
						Unit unit = GameEngine.addUnit(currPlayer, city, city.x, city.y, city.buildingId);
						if (city.hasBuilding(Building.BARRACKS) || city.hasBuilding(Building.BARRACKS_2)
								|| city.hasBuilding(Building.BARRACKS_3))
							unit.veteran = true;
					}
					currPlayer.controller.onNewBuilding(city, city.buildingType, city.buildingId);
				} else {
					currPlayer.controller.onChooseBuilding(city);
				}
				city.hasNewProduct = false;
			} else if (city.hasNewPeople) {
				GameEngine.map.refreshRangeImages(currPlayer, city.x, city.y, (byte) 1, true);
				city.hasNewPeople = false;
				currPlayer.controller.onNewPeople(city);
			} else {
				GameEngine.currCityIndex++;
				return this;
			}
		} else {
			return CheckUnitsStep.getStep();
		}
		if (currPlayer.type != Player.HUMAN) {
			GameEngine.currCityIndex++;
			return this;
		}
		return null;
	}
}
